package com.shop.cereshop.agent.service.behavior.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.shop.cereshop.agent.dao.behavior.AgentBehaviorDAO;
import com.shop.cereshop.agent.page.collect.AgentCollectListVO;
import com.shop.cereshop.agent.page.user.CereAgentUserVO;
import com.shop.cereshop.agent.param.behavior.UpdateCollectDTO;
import com.shop.cereshop.agent.service.behavior.AgentBehaviorService;
import com.shop.cereshop.commons.constant.IntegerEnum;
import com.shop.cereshop.commons.domain.agent.CereAgentRole;
import com.shop.cereshop.commons.domain.behavior.CereAgentBehavior;
import com.shop.cereshop.commons.utils.EmptyUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;

/**
 * @author lx
 */
@Service
public class AgentBehaviorServiceImpl extends ServiceImpl<AgentBehaviorDAO, CereAgentBehavior>
    implements AgentBehaviorService {

  private final AgentBehaviorDAO agentBehaviorDAO;

  public AgentBehaviorServiceImpl(AgentBehaviorDAO agentBehaviorDAO) {
    this.agentBehaviorDAO = agentBehaviorDAO;
  }

  @Override
  public void updateCollect(UpdateCollectDTO param,  CereAgentUserVO user) {
    // 查询用户是否收藏该商品
    CereAgentBehavior cereAgentBehavior = lambdaQuery()
        .eq(CereAgentBehavior::getAgentProductId, param.getAgentProductId())
        .eq(CereAgentBehavior::getAgentUserId, user.getAgentUserId())
        .eq(CereAgentBehavior::getBehaviorType, 2)
        .one();
    if (cereAgentBehavior == null) {
      // 新增收藏记录
      CereAgentBehavior behavior = new CereAgentBehavior();
      behavior.setAgentUserId(user.getAgentUserId())
          .setAgentProductId(param.getAgentProductId())
          .setBehaviorType(2)
          .setCreateTime(LocalDateTime.now())
          .setDeleted(IntegerEnum.YES.getCode());
      save(behavior);
    } else {
      // 查询已有的记录，根据状态取反
      if (cereAgentBehavior.getDeleted().equals(IntegerEnum.YES.getCode())) {
        cereAgentBehavior.setDeleted(IntegerEnum.NO.getCode());
      } else {
        cereAgentBehavior.setDeleted(IntegerEnum.YES.getCode());
      }
      // 更新状态
      updateById(cereAgentBehavior);
    }
  }

  @Override
  public List<AgentCollectListVO> getCollectList(Integer page, Integer pageSize,  CereAgentUserVO user) {
    // 设置分页参数
    PageHelper.startPage(page, pageSize);
    return agentBehaviorDAO.getCollectList(user.getAgentUserId());
  }

  @Override
  public List<AgentCollectListVO> getViewList(Integer page, Integer pageSize,  CereAgentUserVO user) {
    // 设置分页参数
    PageHelper.startPage(page, pageSize);
    return agentBehaviorDAO.getViewList(user.getAgentUserId());
  }

  @Override
  public boolean removeBehaviorByIds(List<Long> behaviorIds) {
    // 参数校验
    if (EmptyUtils.isEmpty(behaviorIds)) {
      return false;
    }

    // 调用父类的removeByIds方法执行删除
    return removeByIds(behaviorIds);
  }
}